package com.fh.controller.building.message;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.building.bill.BillService;
import com.fh.service.building.contract.ContractService;
import com.fh.service.building.message.SysMessageService;
import com.fh.service.building.room.RoomService;
import com.fh.service.role.ShsRoleService;
import com.fh.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/**
 * 站内信
 * Created by Administrator on 2017/10/4.
 */
@Controller
@RequestMapping(value = "/sysMessage")
public class SysMessageController extends BaseController {


    @Resource(name = "sysMessageService")
    private SysMessageService sysMessageService;
    @Resource(name = "contractService")
    private ContractService contractService;
    @Resource(name = "billService")
    private BillService billService;
    @Resource(name = "shsRoleService")
    private ShsRoleService roleService;


    /**
     * 查询列表（所有）
     *
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public PageData list() {
        logBefore(logger, "站内信（查询所有）");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            List<PageData> list = sysMessageService.listAll(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/saveMessage")
    @ResponseBody
    public PageData saveMessage() {
        logBefore(logger, "消息通知");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd.put("CREATE_USERID", user.getUSER_ID()); //创建人ID
            sysMessageService.saveMessage(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }


    /**
     * 新增
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public PageData save() {
        logBefore(logger, "站内信（新增）");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd.put("CREATE_USERID", user.getUSER_ID()); //创建人ID
            pd.put("SEND_NAME", user.getNAME());//发件人
            sysMessageService.saveGg(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 新增 公告
     */
    @RequestMapping(value = "/saveGg")
    @ResponseBody
    public PageData saveGg() {
//        logBefore(logger, "站内信（新增）");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd.put("CREATE_USERID", user.getUSER_ID()); //创建人ID
            pd.put("SEND_NAME", user.getNAME());//发件人
            sysMessageService.saveGg(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public PageData edit() {
        logBefore(logger, "站内信（修改）");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            sysMessageService.edit(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 通过ID获取详情信息
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public PageData info() {
        logBefore(logger, "站内信（详情）");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            PageData data = sysMessageService.findById(pd);
            sysMessageService.changeReadStatus(pd); //变为已读
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 返回list 列表
     */
    @RequestMapping(value = "/json")
    @ResponseBody
    public Object json(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            //测试分页 导出为layui的json数据
            pd = this.getPageData();
            //pd.put("RECEIVER_USERID",user.getUSER_ID());
            pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);//必填 2参
            varList = sysMessageService.list(page);    //列出消息列表
            List<PageData> contract_List = contractService.listcontractingShenHeXX(pd);//检索 代办合同
            List<PageData> bill_List = billService.billshenhelistXX(pd);
            List<Map<String, Object>> messages = (List<Map<String, Object>>) sysMessageService.FindlistAll();
            //messages.get(k).get("CONTRACT_ID");
            //先删除 消息 再增加
            /*for (int i = 0; i < contract_List.size(); i++) {
                for (int k = 0; k < messages.size(); k++) {
                    if (messages.get(k).get("CONTRACT_ID").equals(contract_List.get(i).get("id"))) {
                        PageData pds = new PageData();
                        pds.put("ID", contract_List.get(i).get("id"));
                        sysMessageService.deleteONE(pds);
                    } else {
                        //不存在的代办合同 数据  插入到 消息中
                    }
                }
            }*/
            //先删除 消息 再增加
           /* for (int i = 0; i < bill_List.size(); i++) {
                for (int k = 0; k < messages.size(); k++) {
                    if(messages.get(k).containsKey("BILL_ID")){
                        if (messages.get(k).get("BILL_ID").equals(bill_List.get(i).get("ID"))) {
                            PageData pds = new PageData();
                            pds.put("ID", bill_List.get(i).get("ID"));
                            sysMessageService.deleteONE_BILL(pds);
                        } else {
                            //不存在的代办合同 数据  插入到 消息中
                        }
                    }

                }
            }*/
            //先删除 消息 再增加合同
            /*for(int i=0;i<contract_List.size();i++){
                PageData pds=new PageData();
                pds.put("MESSAGE_ID", UuidUtil.get32UUID());
                pds.put("TITLE","合同提醒");
                pds.put("CONTENT", "您有一条待审核的合同");
                pds.put("TYPE", "1");
                pds.put("RECEIVER_USERID","1");
                pds.put("CONTRACT_ID",contract_List.get(i).get("id"));
                pds.put("BILL_ID","1");//为了 删除消息占用字段
                pds.put("CREATE_USERID", user.getUSER_ID()); //创建人ID
                sysMessageService.save(pds);
            }*/
            //先删除 消息 再增加账单
            /*for(int i=0;i<bill_List.size();i++){
                PageData pds=new PageData();
                pds.put("MESSAGE_ID", UuidUtil.get32UUID());
                pds.put("TITLE","账单提醒");
                pds.put("CONTENT", "您有一条待审核的账单");
                pds.put("TYPE", "1");
                pds.put("RECEIVER_USERID","1");
                pds.put("CONTRACT_ID","1");
                pds.put("BILL_NAME",bill_List.get(i).get("BILL_NAME"));
                pds.put("BILL_ID",bill_List.get(i).get("ID"));//为了 删除消息占用字段
                pds.put("CREATE_USERID", user.getUSER_ID()); //创建人ID
                sysMessageService.save(pds);
            }*/
            datalayui = getLData(page, varList);//必填 3参
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 计算消息数目 为了首页显示用 然后 毫无用处
     *
     * @return
     */
    @RequestMapping(value = "/listindex")
    @ResponseBody
    public PageData listindex() {
        logBefore(logger, "站内信（查询所有）");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            //pd.put("TYPE",1);
            pd.put("ID", user.getUSER_ID());
            //为了显示时间段中的消息 增加 时间参数 为了显示账单提前10天提示消息
            pd.put("PAY_DATE", DateUtil.getAfterDayDate("-10"));
            List<PageData> list = sysMessageService.listindex(pd);
            res.put("data", list.size());
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 去新增页面
     */
    @RequestMapping(value = "/goAdd")
    public ModelAndView goAdd() {
        logBefore(logger, "去新增Room页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            mv.setViewName("building/room/room_edit");
            mv.addObject("msg", "save");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 去合同页面
     */
    @RequestMapping(value = "/goContract")
    public ModelAndView goContract() {
        logBefore(logger, "去新增Room页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            mv.setViewName("building/room/room_edit");
            mv.addObject("msg", "save");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 去修改页面
     */
    @RequestMapping(value = "/goEdit")
    public ModelAndView goEdit() {
        logBefore(logger, "去修改Room页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            pd = sysMessageService.findById(pd);    //根据ID读取
            mv.setViewName("building/room/room_edit");
            mv.addObject("msg", "edit");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteAll")
    @ResponseBody
    public Object deleteAll() {
        logBefore(logger, "批量删除Room");
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            pd = this.getPageData();
            List<PageData> pdList = new ArrayList<PageData>();
            String DATA_IDS = pd.getString("DATA_IDS");
            if (null != DATA_IDS && !"".equals(DATA_IDS)) {
                String ArrayDATA_IDS[] = DATA_IDS.split(",");
                sysMessageService.deleteAll(ArrayDATA_IDS);
                pd.put("msg", "ok");
            } else {
                pd.put("msg", "no");
            }
            pdList.add(pd);
            map.put("list", pdList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return AppUtil.returnObject(pd, map);
    }

    /**
     * 导出到excel
     *
     * @return
     */
    @RequestMapping(value = "/excel")
    public ModelAndView exportExcel() {
        logBefore(logger, "导出Room到excel");
        ModelAndView mv = new ModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("房间号");    //1
            titles.add("楼层");    //2
            titles.add("楼宇id");    //3
            titles.add("房间面积");    //4
            titles.add("创建人id");    //5
            titles.add("创建时间");    //6
            titles.add("排序");    //7
            titles.add("是否删除");    //8
            dataMap.put("titles", titles);
            List<PageData> varOList = sysMessageService.listAll(pd);
            List<PageData> varList = new ArrayList<PageData>();
            for (int i = 0; i < varOList.size(); i++) {
                PageData vpd = new PageData();
                vpd.put("var1", varOList.get(i).getString("ROOM_NUM"));    //1
                vpd.put("var2", varOList.get(i).getString("FLOOR"));    //2
                vpd.put("var3", varOList.get(i).getString("T_ID"));    //3
                vpd.put("var4", varOList.get(i).getString("ROOM_AREA"));    //4
                vpd.put("var5", varOList.get(i).getString("CREATE_ID"));    //5
                vpd.put("var6", varOList.get(i).getString("CREATE_DATE"));    //6
                vpd.put("var7", varOList.get(i).getString("SORT"));    //7
                vpd.put("var8", varOList.get(i).getString("IS_DEL"));    //8
                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv = new ObjectExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }


    /**
     * 个人消息查询列表
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/messjson")
    @ResponseBody
    public PageData messjson() {
//        logBefore(logger, "");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        pd = this.getPageData();
        try {
            pd.put("USER_ID", user.getUSER_ID());
            PageData dataAuth = roleService.authListByLoginUser(pd);
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                String dataStr = "(";
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_1") != -1) {
                    //一级权限
                    dataStr += "\"01\",\"9\",\"12\",\"5\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_2") != -1) {
                    //二级权限
                    dataStr += "\"02\",\"902\",\"1202\",\"502\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_3") != -1) {
                    //三级权限
                    dataStr += "\"03\",\"903\",\"1203\",\"503\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_4") != -1) {
                    //四级权限
                    dataStr += "\"04\",\"904\",\"1204\",\"504\",";
                }
                dataStr += "\"-1\")";
                pd.put("CHECK_STATE", dataStr);
            }

            //权限筛选  --陈豪
            if (dataAuth != null) {
                pd = isAuthUser(dataAuth, pd);
            } else {
                pd.put("beOverdue", "beOverdue");//逾期
                pd.put("expire", "expire");  //将到期
                pd.put("chaobiao", "chaobiao");//抄表
            }
            //为了显示时间段中的消息 增加 时间参数
            pd.put("PAY_DATE", DateUtil.getAfterDayDate("-10"));
            List<PageData> list = sysMessageService.findAllmsessage(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * @Title:权限筛选
     * @reason
     * @author :  陈豪
     * @date 2018/7/2
     */
    public PageData isAuthUser(PageData dataAuth, PageData pd) {
        //  合同查看权限： HTQX_CK ，逾期/收费提醒：CWQX_SF
        String auth_code = dataAuth.getString("AUTH_CODE");
        if (auth_code.indexOf("CWQX_SF") != -1) {
            pd.put("beOverdue", "beOverdue");//逾期

        } else if (auth_code.indexOf("HTQX_CK") != -1) {
            pd.put("expire", "expire");//逾期
        } else if (auth_code.indexOf("CBGL_CB") != -1) {
            pd.put("chaobiao", "chaobiao");//逾期
        }

        return pd;

    }


    /**
     * 查看消息功能中：修改账单的更新时间和是否已读
     *
     * @return
     */
    @RequestMapping(value = "/updatezd")
    @ResponseBody
    public PageData updatezd() {
        logBefore(logger, "站内信（详情）");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            pd.put("UPDATE_DATE", new DateUtil().getTime());
            pd.put("IS_READ", "0");
            sysMessageService.updatezd(pd); //变为已读和更新时间
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 查看消息功能中：修改合同的更新时间和是否已读
     *
     * @return
     */
    @RequestMapping(value = "/updateht")
    @ResponseBody
    public PageData updateht() {
        logBefore(logger, "站内信（详情）");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            pd.put("UPDATE_DATE", new DateUtil().getTime());
            pd.put("IS_READ", 0);
            sysMessageService.updateht(pd); //变为已读
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 公告查询列表
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/noticejson")
    @ResponseBody
    public PageData noticejson() {
//        logBefore(logger, "");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd.put("ID", user.getUSER_ID());
            List<PageData> list = sysMessageService.findAllnotice(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 公告功能中：修改公告是否已读
     *
     * @return
     */
    @RequestMapping(value = "/updatenotice")
    @ResponseBody
    public PageData updatenotice() {
//        logBefore(logger, "站内信（详情）");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            pd.put("IS_READ", "1");
            sysMessageService.updatenotice(pd); //变为已读和更新时间
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 通过公告ID查询单个公告
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/findnotice")
    @ResponseBody
    public PageData findnotice() {
//        logBefore(logger, "站内信（详情）");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            PageData data = sysMessageService.findById(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /* ===============================权限================================== */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }
    /* ===============================权限================================== */

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }


}
